import { NextRequest, NextResponse } from 'next/server';
import { SessionRepository } from '@/lib/database/repositories/session-repository';
import { SESSION_COOKIE_NAME, ClientInfo } from '@/lib/types/session';

// 使用Map缓存最近的访问记录，防止短时间内重复计数
const visitCache = new Map<string, number>();

// 定期清理缓存(5分钟)
setInterval(() => {
  const now = Date.now();
  for (const [key, timestamp] of visitCache.entries()) {
    if (now - timestamp > 5 * 60 * 1000) {
      visitCache.delete(key);
    }
  }
}, 60 * 1000);

// 从请求中获取客户端信息
function getClientInfo(request: NextRequest): ClientInfo {
  const userAgent = request.headers.get('user-agent') || undefined;
  const referrer = request.headers.get('referer') || undefined;
  
  // 从请求头中获取 IP 地址
  const forwardedFor = request.headers.get('x-forwarded-for');
  const realIp = request.headers.get('x-real-ip');
  const ipAddress = forwardedFor 
    ? forwardedFor.split(',')[0].trim() 
    : (realIp || undefined);
  
  // 简单的设备类型检测
  let deviceType = 'unknown';
  if (userAgent) {
    if (/mobile|android|iphone|ipod/i.test(userAgent)) {
      deviceType = 'mobile';
    } else if (/tablet|ipad/i.test(userAgent)) {
      deviceType = 'tablet';
    } else {
      deviceType = 'desktop';
    }
  }
  
  return { ipAddress, userAgent, referrer, deviceType };
}

export async function POST(request: NextRequest) {
  try {
    const { path } = await request.json();
    
    // 从请求cookie中获取会话ID
    const sessionId = request.cookies.get(SESSION_COOKIE_NAME)?.value;
    
    if (!sessionId) {
      return NextResponse.json(
        { error: '缺少会话ID' }, 
        { status: 400 }
      );
    }
    
    // 生成唯一缓存键
    const cacheKey = `${sessionId}:${path}`;
    const now = Date.now();
    
    // 防止短时间内重复记录
    if (visitCache.has(cacheKey)) {
      const lastTime = visitCache.get(cacheKey)!;
      if (now - lastTime < 30 * 1000) { // 30秒内的重复访问忽略
        return NextResponse.json({ message: '忽略短时间内的重复访问' });
      }
    }
    
    // 更新缓存
    visitCache.set(cacheKey, now);
    
    // 验证会话是否有效
    const session = await SessionRepository.getById(sessionId);
    
    if (!session || session.expiresAt < new Date()) {
      console.log('无效会话，跳过访问统计', { sessionId });
      return NextResponse.json({ 
        success: false, 
        message: '无效会话ID'
      });
    }
    
    // 获取客户端信息
    const clientInfo = getClientInfo(request);
    
    // 只有会话有效时才更新访问记录，同时更新客户端信息
    SessionRepository.recordVisit(sessionId, path, clientInfo)
      .then(() => console.log('访问记录已更新', { sessionId, path }))
      .catch(err => console.error('访问记录更新失败', err));
    
    return NextResponse.json({ success: true });
    
  } catch (error) {
    console.error('记录访问失败:', error);
    return NextResponse.json(
      { error: '记录访问失败' },
      { status: 500 }
    );
  }
} 